<template>
  <list
      :headers="headers"
      isMultiSelect
      isHasOperateColumn
      :searchUrl="data.searchUrl"
      v-model="searchParams"
      :operateColumnWidth="300"
      ref="listRef">
    <template #operateBtnsSlot="{ selectData }">
      <v-button type="primary" @click="createRole" text="新增角色" v-permission="`btn.Role.add`"></v-button>
      <v-button
          type="danger"
          :disabled="!Boolean(selectData.data.length)"
          @click="batchDelete(selectData)"
          text="批量删除"
      />
    </template>
    <template #operateSlot="scope">
      <v-button @click="assignPermissions(scope.row)" text="分配权限" v-permission="`btn.Role.assign`"/>
      <v-button type="danger" @click="deleteHandle(scope.row)" text="删除"
                v-permission="`btn.Role.remove`"/>
      <v-button type="primary" text="编辑" v-permission="`btn.Role.update`"/>
    </template>
    <template #searchSlot>
      <v-input label="职位" v-model="searchParams.jobTitle"/>
    </template>
  </list>
  <el-drawer
      v-model="data.isShowDrawer"
      :title='`分配 "${data.currentRoleName}" 菜单与按钮的权限`'
      direction="rtl"
      :before-close="handleClose"
      :style="{width: '18%'}"
  >
    <el-tree
        :data="data.treeData"
        show-checkbox
        node-key="id"
        :props="defaultProps"
        default-expand-all
        ref="menuTree"
        :default-checked-keys="data.defaultCheckedKeys"
    />
    <template #footer>
      <el-button @click="()=>data.isShowDrawer=false">取消</el-button>
      <el-button type="primary" @click="savePermissions">确定</el-button>
    </template>
  </el-drawer>
</template>
<script lang="ts" setup>
import {reactive, watch, ref, inject} from 'vue'
import {getRolePermissionByIdApi, savePermissionsApi, deleteRoleApi} from "@/api/role";
import {ElMessage} from "@/components";

interface RoleManageState {
  searchUrl: string,
  isShowDrawer: boolean,
  treeData: Menu[],
  currentRoleId: number,
  defaultCheckedKeys: string | number[],
  currentRoleName: string
}

const defaultProps = {
  children: 'children',
  label: 'name',
}

const menuTree = ref();
const listRef = ref()
const headers = reactive<TableHeader[]>([
  {
    prop: 'id',
    label: 'ID'
  },
  {
    prop: 'jobTitle',
    label: '职位名称'
  },
  {
    prop: 'createdTime',
    label: '创建时间'
  },
  {
    prop: 'updatedTime',
    label: '更新时间'
  }
])

let $messageBox: any = inject('$messageBox')
let $message: any = inject('$message')

let searchParams = reactive({
  jobTitle: ''
})

const data = reactive<RoleManageState>({
  searchUrl: '/role/list',
  isShowDrawer: false,
  treeData: [],
  currentRoleId: 0,
  defaultCheckedKeys: [],
  currentRoleName: ''
})

watch(() => data.isShowDrawer, (value) => {
  if (value) {
    data.defaultCheckedKeys = []
    getRolePermissionById()
  }
})

const getRolePermissionById = async () => {
  const res = await getRolePermissionByIdApi(data.currentRoleId)
  if (res.status === 0) {
    data.treeData = res.data;
    data.defaultCheckedKeys = findSelectMenu(res.data, [])
  }
}

const findSelectMenu = (treeData, initArr) => {
  treeData.forEach((item) => {
    if (item.select && item.level === 4) {
      initArr.push(item.id)
    }
    if (item.children && item.children.length > 0) {
      findSelectMenu(item.children, initArr)
    }
  })
  return initArr;
}

const deleteHandle = (row) => {
  $messageBox.confirm(
      `确定删除${row.jobTitle}吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    deleteRoleApi(row.id).then(res => {
      if (res.status === 0) {
        $message.success('删除成功')
        listRef.value.searchData()
      } else {
        $message.error('删除失败')
      }
    })
  })
}

const handleClose = (done: () => void) => {
  done()
}

const batchDelete = (scope: any) => {
  console.log(scope)
}


const assignPermissions = (row) => {
  data.isShowDrawer = true;
  data.currentRoleId = row.id;
  data.currentRoleName = row.jobTitle;
}

const savePermissions = async () => {
  const arr1 = menuTree.value.getCheckedKeys()
  const arr2 = menuTree.value.getHalfCheckedKeys()
  const permissionId = arr1.concat(arr2).join(',')
  if (permissionId) {
    const res = await savePermissionsApi({roleId: data.currentRoleId, permissionId})
    if (res.status === 0) {
      // ElMessage
      data.isShowDrawer = false;
      ElMessage({
        type: 'success',
        message: '分配权限成功'
      })
    }
  } else {
    ElMessage({
      type: 'warning',
      message: '请选择权限'
    })
  }

}

const createRole = () => {

}
</script>
<style scoped lang="scss">
.el-drawer {
  width: 20%;
}
</style>
